package com.blyat.xsoft.kernel.component.security;

import com.blyat.xsoft.kernel.component.security.exception.SecureException;
import com.blyat.xsoft.kernel.component.security.exception.code.SecurityErrorResult;
import com.blyat.xsoft.kernel.restful.view.ResultModel;
import com.blyat.xsoft.kernel.util.ServletUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author syh
 * @date 2019/8/21
 **/
public class SecurityLoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
        if (ServletUtil.isAjaxRequest()) {
            ServletUtil.writer(ResultModel.FAIL(new SecureException(SecurityErrorResult.AUTH_FAILURE)));
        } else {
            String errorPage = "/error";
            request.getRequestDispatcher(errorPage).forward(request, response);
        }
    }
}
